<?php
namespace app\admin\controller;
use think\Validate;
use think\Db;
use think\Session;
use app\common\model\Warehouse;
use app\common\model\Room;
use app\common\model\Roominfo;
use app\common\model\Otpurchaseclass;
use app\common\model\Otpurchaseinfo;
use app\common\model\Goods;
use app\admin\library\Excel;

use app\common\model\Otsaleclass;
use app\common\model\Otsaleinfo;



class WarehouseController extends BaseController
{
    // 视图
    public function stock()
    {
        return view();
    }
    public function room()
    {
        return view();
    }
    public function otpurchase()
    {
        return view();
    }
    // 添加入库
    public function add_otpurchase(){
        return view();
    }
    public function otsale(){
        return view();
    }
    public function add_otsale(){
        return view();
    }
    public function pandian(){
        return view();
    }


    //仓库列表
    public function warehouse_list(){
        $where = array_filter(input('post.'));
        $page = max(input('get.page',0),1);
        $page_size = 10;
        $total = Warehouse::where($where)->count();
        $rows = Warehouse::where($where)->order('id desc')->page($page,$page_size)->select();
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    //新增|更新仓库信息
    public function set_warehouse(){
        $input=input('post.');
        if(isset($input['id'])){
            if(empty($input['id'])){
                //新增
                $validate = new Validate([
                    ['name','require','仓库名称不能为空'],
                ]);
                $vali = $validate->check($input);
                $input['py']= '';//首拼信息
                if($vali===true){
                    $create_info=Warehouse::create($input);
                    $this->success('添加成功');
                }else{
                    $this->error($validate->getError());
                }
            }else{
                //更新
                $validate = new Validate([
                    ['name','require','仓库名称不能为空'],
                ]);
                $vali = $validate->check($input);
                if($vali===true){
                    $input['py'] = '';//首拼信息
                    $update_info=Warehouse::update($input);
                    $this->success('修改成功');
                }else{
                    $this->error($validate->getError());
                }
            }
        }else{
            $this->error('传入参数不完整');
        }
    }
    //删除仓库信息
    public function del_warehouse($id){
        $res = Warehouse::where('id',$id)->delete();
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    //库存查询
    public function room_list(){
        $where = array_filter(input('post.'));
        // if(!empty($where['name'])){
        //     $goodsIds = Goods::where('name','like', '%'.$where['name'].'%')->column('id');
        //     $where['goods'] = ['in',$goodsIds];
        //     unset($where['name']);
        // }
        if(!empty($where['brand_name']) || !empty($where['cate_name']) || !empty($where['keyword'])){
            if(!empty($where['brand_name'])){
                $goods_where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
                unset($where['brand_name']);
            }
            if(!empty($where['cate_name'])){
                $goods_where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
                unset($where['cate_name']);
            }
            if(!empty($where['keyword'])){
                $goods_where['name'] = ['like','%'.$where['keyword'].'%'];
                unset($where['keyword']);
            }
            $goodsIds = Goods::where($goods_where)->column('id');
            $where['goods'] = ['in',$goodsIds];
        }

        if(!empty($where['number'])||!empty($where['tel'])){
            $whereWarehouse = [];
            if(!empty($where['number'])){
                $whereWarehouse['number'] = ['like','%'.$where['number'].'%'];
                
                unset($where['number']);
            }
            if(!empty($where['tel'])){
                $whereWarehouse['tel'] = ['like','%'.$where['tel'].'%'];
                unset($where['tel']);
            }
            $warehouseIds = Warehouse::where($whereWarehouse)->column('id');
            $where['warehouse'] = ['in',$warehouseIds];

        }
        // $whereOr = [];
        // if(!empty($where['keyword'])){
        //     $whereOr['origin_price'] =  ['like','%'.$where['keyword'].'%'];
        //     $whereOr['nums'] =  ['like','%'.$where['keyword'].'%'];
        //     $whereOr['origin_price'] =  ['like','%'.$where['keyword'].'%'];
        //     unset($where['keyword']);
        // }
        
        $page = max(input('get.page',0),1);
        $page_size = 10;
        $total = Room::where($where)->count();
        $rows = Room::where($where)->with(['warehouseinfo','goodsinfo' => ['brandInfo','cateInfo']])->order('id desc')->page($page,$page_size)->select()->toArray();
        foreach ($rows as $key => &$item) {
            if(!empty($item['goodsinfo'])){
                $item['goodsinfo']['picture'] = config('upload_path') . $item['goodsinfo']['picture'];
                $item['goodsinfo']['pic_tmb'] = $this->getThumb($item['goodsinfo']['picture']);
            }
            // 前端盘点 字段
            $item['stock'] = '';
            $item['check'] = '';
            
        }
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    //库存查询 导出
    public function room_list_export(){
        $where = array_filter(input('get.'));
        Excel::room_list_export($where);
    }
    // 库存查询---删除
    public function del_room($id){
        $room_class = Room::where ('id',$id)->find();

        if($room_class['nums'] > 0){
            $this->error('有库存，不可删除');
        }
        $res = Room::where ('id',$id)->delete();
        $res = Roominfo::where ('pid',$id)->delete();
        $this->success('成功','',$res);
    }
     // 库存查询---详情
     public function room_info($id){
        $page = $this->request->param('page');
        $page_size = $this->request->param('page_size');
        if(empty($page_size)){
            $page_size = 10;
        }
        $data = Roominfo::where ('pid',$id)->paginate($page_size, false, ['query' => request()->param(),'page'=>$page])->toArray();
        $data2 = $data['data'];
        foreach ($data2 as $key => &$value) {
            if($value['type'] == 7){
                // 其它入库单
                $Otpurchaseclass = Otpurchaseclass::where('id',$value['class'])->find();
                if(!empty($Otpurchaseclass)){
                    $value['number'] = $Otpurchaseclass['number'];
                    $value['auditingtime'] = date('Y-m-d', $Otpurchaseclass['auditingtime']);
                    if($Otpurchaseclass['pagetype'] == 1){
                        $value['typeName'] = '盘盈单';
                    }else if($Otpurchaseclass['pagetype'] === 0){
                        $value['typeName'] = '其它入库单';
                    }
                    
                }

            }else if($value['type'] == 8){
                // 其它出库单
                $Otsaleclass = Otsaleclass::where('id',$value['class'])->find();
                if(!empty($Otsaleclass)){
                    $value['number'] = $Otsaleclass['number'];
                    $value['auditingtime'] = date('Y-m-d', $Otsaleclass['auditingtime']);
                    if($Otsaleclass['pagetype'] == 1){
                        $value['typeName'] = '盘亏单';
                    }else if($Otsaleclass['pagetype'] === 0){
                        $value['typeName'] = '其它出库单';
                    }
                }

            }
        }
        $data['data'] = $data2;
        // dump($data);
        $this->success('成功','',$data);
    }
    /**
     * 库存总数和总数量
     */
    public function room_total(){
        $where = array_filter(input('post.'));
        if(!empty($where['brand_name']) || !empty($where['cate_name']) || !empty($where['keyword'])){
            if(!empty($where['brand_name'])){
                $goods_where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
                unset($where['brand_name']);
            }
            if(!empty($where['cate_name'])){
                $goods_where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
                unset($where['cate_name']);
            }
            if(!empty($where['keyword'])){
                $goods_where['name'] = ['like','%'.$where['keyword'].'%'];
                unset($where['keyword']);
            }
            $goodsIds = Goods::where($goods_where)->column('id');
            $where['goods'] = ['in',$goodsIds];
        }

        if(!empty($where['number'])||!empty($where['tel'])){
            $whereWarehouse = [];
            if(!empty($where['number'])){
                $whereWarehouse['number'] = ['like','%'.$where['number'].'%'];
                
                unset($where['number']);
            }
            if(!empty($where['tel'])){
                $whereWarehouse['tel'] = ['like','%'.$where['tel'].'%'];
                unset($where['tel']);
            }
            $warehouseIds = Warehouse::where($whereWarehouse)->column('id');
            $where['warehouse'] = ['in',$warehouseIds];

        }
        $count = Room::where($where)->count();
        $sum = Room::where($where)->sum('nums');
        $sum_price = Room::where($where)->sum('nums*origin_price');

        $this->success('成功','',['count' => $count,'sum' => $sum, 'sum_price' => $sum_price]);

    }

    //其它入库-报表列表
    public function otpurchase_list(){
        $where = array_filter(input('post.'));
        if(input('post.pagetype') === '0'){
            $where['pagetype'] = 0;
        }

        // 处理商品名称查询
        if(isset($where['name'])){
            $goodsIds = Goods::where('name','like', '%'.$where['name'].'%')->column('id');
            $otpurchaseIds = Otpurchaseinfo::where(['goods' => ['in',$goodsIds]])->column('pid');
            $where['id'] = ['in',$otpurchaseIds];
            unset($where['name']);
        }
        $page = max(input('get.page',0),1);
        $page_size = 10;

        $total = Otpurchaseclass::where ($where)->count();//获取总条数
        $rows = Otpurchaseclass::with('userinfo')->where($where)->page($page,$page_size)->order('id desc')->select();//查询分页数据
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    //其它入库详情
    public function otpurchase_info($id){
        $where = array_filter(input('post.'));

        // 处理商品名称查询
        $page = max(input('get.page',0),1);
        $page_size = 10;

        $total = Otpurchaseinfo::where ('pid',$id)->count();//获取总条数
        $rows = Otpurchaseinfo::with('goodsinfo')->where('pid',$id)->page($page,$page_size)->order('id desc')->select();//查询分页数据
        foreach ($rows as $key => &$item) {
            if(!empty($item['goodsinfo'])){
                $item['goodsinfo']['picture'] = config('upload_path') . $item['goodsinfo']['picture'];
                $item['goodsinfo']['pic_tmb'] = $this->getThumb($item['goodsinfo']['picture']);
            }
        }
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    //其它入库-删除
    public function del_otpurchase($id){
        $Otpurchaseclass = Otpurchaseclass::where ('id',$id)->find();

        if($Otpurchaseclass['type'] == 1){
            $this->error('已审核，不可删除');
        }
        $res = Otpurchaseclass::where ('id',$id)->delete();
        $res = Otpurchaseinfo::where ('pid',$id)->delete();
        $this->success('成功','',$res);
    }

    // 添加入库
    public function set_otpurchase(){

        $input = input('post.');

        // 验证表单
        $valiInfo =  array_merge($input['info'],['items' => isset($input['items']) ? $input['items'] : [] ]);
        $validate = new Validate([
            ['time','require','单据日期不能为空'],
            ['number','require','单据编号不能为空'],
            ['pagetype','require','单据类型不能为空'],
            ['items','require','商品不能为空'],
        ]);
        $vali = $validate->check($valiInfo);
        if(!$vali){
            $this->error($validate->getError());
        }
        // 验证商品属性不能为空
        $validate = new Validate([
            ['spec','require','请选择尺码'],
        ]);
        foreach ($input['items'] as $goods_key => $row) {
            if (!$validate->check($row)) {
                return [
                    'code'  => 0,
                    'msg'   => $validate->getError()
                ];
            }
        }

        // 获取制单人
        $user = Session::get('uid');
        $input['info']['user'] = $user;
        $input['info']['type'] = 0;
        $input['info']['time'] = strtotime($input['info']['time']);

        

        Db::transaction(function() use($input){
            $items = $input['items'];
            $info = $input['info'];
            $create_info=Otpurchaseclass::create($info);
            $info_pid=$create_info['id'];
            foreach ($input['items'] as $info_vo) {
                $info_vo['pid']=$info_pid;
                $info_vo['attr']='';//兼容辅助属性
                // var_dump($info_vo);
                 $otpurchaseinfoModel =  new Otpurchaseinfo();
                 $otpurchaseinfoModel->allowField(true)->save($info_vo);
            }

        });
        $this->success('成功','',[]);
    }
    //审核
    public function auditing($id){
        if(empty($id)){
            $this->error('传入参数不完整!');
        }else{
            Db::transaction(function() use($id){
                //实际操作
                $class=Otpurchaseclass::where(['id'=>$id])->find();
                $info=Otpurchaseinfo::where(['pid'=>$id])->select();
                    //审核操作
                foreach ($info as $info_vo) {
                    //获取仓储信息
                    $room_sql=[];
                    $room_sql['warehouse']=$info_vo['warehouse'];
                    $room_sql['goods']=$info_vo['goods'];
                    $room_sql['attr']=isset($info_vo['attr']['nod']) ? $info_vo['attr']['nod'] : '';
                    $room_sql['batch']=$info_vo['batch'];
                    $room_sql['spec']=$info_vo['spec'];
                    $room_sql['color']=$info_vo['color'];
                    $room_sql['origin_price']=$info_vo['origin_price'];
                    $room=Room::where($room_sql)->find();
                    //设置仓储信息
                    if(empty($room)){
                        //新增仓储数据
                        $room_sql['nums']=$info_vo['nums'];
                        $room=Room::create($room_sql);
                    }else{
                        Room::where(['id'=>$room['id']])->setInc('nums',$info_vo['nums']);//更新仓储数据[+]
                    }
                    //新增仓储详情
                    $roominfo_sql['pid']=$room['id'];
                    $roominfo_sql['type']=7;
                    $roominfo_sql['class']=$id;
                    $roominfo_sql['info']=$info_vo['id'];
                    $roominfo_sql['nums']=$info_vo['nums'];
                    Roominfo::create($roominfo_sql);
                    Otpurchaseinfo::update(['id'=>$info_vo['id'],'room'=>$room['id']]);//更新INFO数据
                }
                Otpurchaseclass::update(['id'=>$id,'type'=>1,'auditinguser'=>Session::get('uid'),'auditingtime'=>time()]);//更新CLASS数据
               
    
            });
            $this->success('成功','',[]);
        }
    }
    // 其它出库单
    //其它出库-报表列表
    public function otsale_list(){
        $where = array_filter(input('post.'));
        if(input('post.pagetype') === '0'){
            $where['pagetype'] = 0;
        }

        // 处理商品名称查询
        if(isset($where['name'])){
            $goodsIds = Goods::where('name','like', '%'.$where['name'].'%')->column('id');
            $otpurchaseIds = Otsaleinfo::where(['goods' => ['in',$goodsIds]])->column('pid');
            $where['id'] = ['in',$otpurchaseIds];
            unset($where['name']);
        }
        $page = max(input('get.page',0),1);
        $page_size = 10;

        $total = Otsaleclass::where ($where)->count();//获取总条数
        $rows = Otsaleclass::with('userinfo')->where($where)->page($page,$page_size)->order('id desc')->select();//查询分页数据
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    //其它入库详情
    public function otsale_info($id){
        $where = array_filter(input('post.'));

        // 处理商品名称查询
        $page = max(input('get.page',0),1);
        $page_size = 10;

        $total = Otsaleinfo::where ('pid',$id)->count();//获取总条数
        $rows = Otsaleinfo::with('goodsinfo')->where('pid',$id)->page($page,$page_size)->order('id desc')->select();//查询分页数据
        foreach ($rows as $key => &$item) {
            if(!empty($item['goodsinfo'])){
                $item['goodsinfo']['picture'] = config('upload_path') . $item['goodsinfo']['picture'];
                $item['goodsinfo']['pic_tmb'] = $this->getThumb($item['goodsinfo']['picture']);
            }
        }
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
     // 添加出库
     public function set_otsale(){

        $input = input('post.');

        // 验证表单
        $valiInfo =  array_merge($input['info'],['items' => isset($input['items']) ? $input['items'] : [] ]);
        $validate = new Validate([
            ['time','require','单据日期不能为空'],
            ['number','require','单据编号不能为空'],
            ['pagetype','require','单据类型不能为空'],
            ['items','require','商品不能为空'],
        ]);
        $vali = $validate->check($valiInfo);
        if(!$vali){
            $this->error($validate->getError());
        }

        // 获取制单人
        $user = Session::get('uid');
        $input['info']['user'] = $user;
        $input['info']['type'] = 0;
        $input['info']['time'] = strtotime($input['info']['time']);

        

        Db::transaction(function() use($input){
            $items = $input['items'];
            $info = $input['info'];
            $create_info=Otsaleclass::create($info);
            $info_pid=$create_info['id'];
            foreach ($input['items'] as $info_vo) {
                $info_vo['pid']=$info_pid;
                $info_vo['attr']='';//兼容辅助属性
                // var_dump($info_vo);
                 $otpurchaseinfoModel =  new Otsaleinfo();
                 $otpurchaseinfoModel->allowField(true)->save($info_vo);
            }

        });
        $this->success('成功','',[]);
    }
    //审核
    public function auditing_otsale($id){
        if(empty($id)){
            $this->error('传入参数不完整!');
        }else{
            Db::transaction(function() use($id){
                //实际操作
                $class=Otsaleclass::where(['id'=>$id])->find();
                $info=Otsaleinfo::where(['pid'=>$id])->select();
                    //审核操作
                foreach ($info as $info_vo) {
                    //设置仓储信息
                    Room::where(['id'=>$info_vo['room']])->setDec('nums',$info_vo['nums']);//更新仓储数据[-]
                    //新增仓储详情
                    $roominfo_sql['pid']=$info_vo['room'];
                    $roominfo_sql['type']=8;
                    $roominfo_sql['class']=$id;
                    $roominfo_sql['info']=$info_vo['id'];
                    $roominfo_sql['nums']=$info_vo['nums'];
                    Roominfo::create($roominfo_sql);
                }
                Otsaleclass::update(['id'=>$id,'type'=>1,'auditinguser'=>Session::get('uid'),'auditingtime'=>time()]);//更新CLASS数据
               
            });
            $this->success('成功','',[]);
        }
    }
    //其它出库-删除
    public function del_otsale($id){
        $Otpurchaseclass = Otsaleclass::where ('id',$id)->find();

        if($Otpurchaseclass['type'] == 1){
            $this->error('已审核，不可删除');
        }
        $res = Otsaleclass::where ('id',$id)->delete();
        $res = Otsaleinfo::where ('pid',$id)->delete();
        $this->success('成功','',$res);
    }
}